package com.example.synchost5.job;

import com.example.synchost5.store.DataStore;
import com.example.synchost5.thirdparty.API;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Async
@Component
public class FetchInfoJob {

    private static final Logger logger = LoggerFactory.getLogger(FetchInfoJob.class);

    @Autowired
    private DataStore dataStore;

    @Autowired
    private API api;

    /**
     * 每 3 小时进行一次数据更新
     */
    @Scheduled(cron = "0 * */3 * * *")
    public void autoFetch() {
        logger.info("auto fetch start at: " + new Date());
        Map<String, String> addressPool = dataStore.allIPData();
        if (addressPool != null && !addressPool.isEmpty()) {
            for (Map.Entry<String, String> pair : addressPool.entrySet()) {
                String domain = pair.getKey();
                String ip = api.fetch(pair.getKey());
                logger.info(domain + " - " + ip);
                if (ip != null) {
                    dataStore.updateIP(domain, ip);
                }
            }
        }
        logger.info("auto fetch finish at: " + new Date());
    }
}
